<?php
/* This file is part of Mirasol CMS
   (C) 2011 by Alban Technologies. Written by Chris Alban Hansen.
   Released under the terms of the GNU General Public License.
   See COPYING in the top level directory of the Mirasol CMS installation. */

include "{$_SERVER['DOCUMENT_ROOT']}/includes/config.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/db.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/login.php";

$connection = db_open ();

$result = mysql_query ("SELECT id FROM ".db_maketablename ($table_users)." WHERE username LIKE 'admin'");
$adminexists = mysql_num_rows ($result) == 0 ? 0 : 1;
mysql_free_result ($result);

if ($adminexists == 1 && $login['username'] == "")
{
  header ("location: ./");
  exit;
}

if (isset ($_POST['fullname']) &&
    isset ($_POST['username']) &&
    isset ($_POST['email']) &&
    isset ($_POST['passwd']) &&
    isset ($_POST['passwdcheck']))
{
  $salt = time ();
  $email = mysql_real_escape_string (trim ($_POST['email']));
  $fullname = mysql_real_escape_string (trim ($_POST['fullname']));
  $username = mysql_real_escape_string (trim ($_POST['username']));
  $passwd = trim ($_POST['passwd']);
  $passwdcheck = trim ($_POST['passwdcheck']);
  $passwdenc = md5 ($passwd.$salt);
  $rights = 0;
  if ($_POST['rights_admin'] == "on")
    $rights |= $rights_admin;
  
  /* Are the two passwords identical? */
  if ($passwd == $passwdcheck)
    {
      /* Check to see if we already have the email registered before we add the new user */
      $query = "SELECT email FROM ".db_maketablename ($table_users)." WHERE email='$email' LIMIT 1";
      $result = mysql_query ($query);
      /* Here we go... */
      if (mysql_num_rows ($result) < 1)
        mysql_query ("INSERT INTO ".db_maketablename ($table_users)." (fullname, username, email, passwd, salt, rights) values ('$fullname', '$username', '$email', '$passwdenc', '$salt', '$rights')");
      mysql_free_result ($result);
    }
}

db_close ($connection);
header ("location:$app_adminpath/");
exit;
?>
